import axios from 'axios'
import { Message } from 'element-ui'
import store from "@/utils/store";

// todo 迭代更新ajax请求方式
// create an axios instance
const service = axios.create({
  baseURL: '/', // api 的 base_url
  timeout: 6000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.get('token')) {
      let token = store.get('token')
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  // response => response,
  async response => {
    // todo 成功之后封装
    return response.data
  },
  error => {
    const status = error.response.status
    switch (status) {
      case 401: {
        const msg = '登陆信息过期！请重新登录！'
        Message({ message: msg, type: 'error', duration: 5 * 1000 })
        // location.reload()
        // router.push({ name: 'Login' })
        break
      }
      case 400: {
        // error.response.data.message
        const msg = error.response.data.message || '请求参数错误！'
        Message({ message: msg, type: 'error', duration: 5 * 1000 })
        // Loading.close()
        break
      }
      case 404: {
        const msg = '请求接口异常或不存在！'
        Message({ message: msg, type: 'error', duration: 5 * 1000 })
        break
      }
      default : {
        Message({
          message: error.message,
          type: 'error',
          duration: 5 * 1000
        })
      }
    }
    return Promise.reject(error)
  }
)

export default service
